// var express = require('express');
// var router = express.Router();
// var Books = require("../data/books")
// var Reviews = require("../data/reviews")

const express = require('express');
const router = express.Router();
const data = require('../data');
const Books = data.books;
const Reviews = data.reviews;

router.post('/', async function (req, res, next) {
  let booksData = {
    title: "the shing",
    author: { authorFirstName: "stepgen", authorLastaName: "king" },
    genre: ["novie", "hoone", "goggeqw", "phtyyds"],
    datePublished: "1/27/1977",
    summary: "jack and roold new job can this is summary"
  }
  let valid = await Books.validation(booksData)
  if (valid.flag) {
    let result = await Books.saveBooks(booksData)
    res.json({ status: 1, msg: "add success" })
  } else {
    console.log(valid.error)
    res.sendStatus(400)
    return
  }

});

router.get("/", async function (req, res, next) {
  let result = await Books.findAll()
  res.json(result)
})
router.get("/:id", async function (req, res, next) {
  try {
    // console.log(req.body)
    let result = await Books.findOne(req.params.id)
    res.json(result)
  } catch (err) {
    res.sendStatus(404)
    return
  }

})
router.delete("/:id", async function (req, res, next) {
  try {
    // console.log(req.body)
    let result = await Books.deleteBooks(req.params.id)
    let deleteR = await Reviews.deleteAllReviews(req.params.id)
    res.json(result)
  } catch (err) {
    res.sendStatus(404)
    return
  }

})
router.put("/:id", async function (req, res, next) {
  try {
    // console.log(req.body)
    let booksData = req.body || {
      title: "the shing111",
      author: { authorFirstName: "stepgen", authorLastaName: "king" },
      genre: ["novie", "hoone", "goggeqw", "phtyyds"],
      datePublished: "1/27/1977",
      summary: "jack and roold new job can this is summary"
    }
    let valid = await Books.validation(booksData)
    if (valid.flag) {

      let result = await Books.updateOne(req.params.id, booksData)

      res.json(result)
    }

  } catch (err) {
    res.sendStatus(404)
    return
  }

})
module.exports = router;
